﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ExtAspNet;
using SubSonic;
using System.Collections;

namespace TCMSystem.business.enterprise
{
    public partial class company_picture : PageBase
    {
        private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        #region 模块类型
        /// <summary>
        /// 当前页面所属的模块
        /// </summary>
        public override ModuleType Module
        {
            get
            {
                return ModuleType.BizCompany;
            }
        }
        #endregion 模块类型

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        private void LoadData()
        {
            //// 权限检查
            //if (!CheckPowerEdit())
            //{
            //    CheckPowerFailWithPage();
            //    return;
            //}

            // 权限检查
            CheckPowerWithButton(ModulePowerType.BizCompany_DeletePicture,this.btnDeleteSelected);
            CheckPowerWithButton(ModulePowerType.BizCompany_UploadPicture,this.btnUpload);
            ResolveDeleteButtonForGrid(this.btnDeleteSelected, this.gridEnterprisePicture);

            btnClose.OnClientClick = ActiveWindow.GetConfirmHidePostBackReference();

            this.BindGrid();
           
        }
        #endregion


        private void BindGrid()
        {
            int intEnterpriseId = GetQueryIntValue("id");
            TblBizEnterprise current = TblBizEnterprise.FetchByID(intEnterpriseId);
            if (current == null)
            {
                // 参数错误，首先弹出Alert对话框然后关闭弹出窗口
                Alert.Show("参数错误！", String.Empty, ActiveWindow.GetHideReference());
                return;
            }

            // 企业图片（逗号分隔字符串转换为数组）
            ArrayList arrlstPics = StringUtil.ConvertCommaStringToArray(current.EnterprisePicture);

            // 返回图片数据
            SqlQuery q = new Select().From<TblBizPicture>();

            if (arrlstPics.Count == 0)
            {
                q.Where("1").IsNotEqualTo("1");
            }
            else
            {
                q.Where(TblBizPicture.PictureIdColumn).In(arrlstPics);
            }

            TblBizPictureCollection items = q.ExecuteAsCollection<TblBizPictureCollection>();

            this.gridEnterprisePicture.DataSource = items;
            this.gridEnterprisePicture.DataBind();
            
            // 厂区图片最多3张
            if (items.Count >= 3)
            {
                this.btnUpload.Enabled = false;
            }
            else
            {
                this.btnUpload.Enabled = true;
            }

        }

        /// <summary>
        /// 图片上传
        /// </summary>
        /// <returns>图片ID</returns>
        private string UploadImage()
        {
            //TODO:文件类型限制没做
            //TODO:参看http://www.extasp.net/forum.php?mod=viewthread&tid=372&highlight=FileUpload

            // 原文件名
            string strOrgImageName = fileEnterprisePicture.ShortFileName;
            if (strOrgImageName == string.Empty)
            {
                return string.Empty;
            }

            // 上传图片的相对路径
            string filePath = GetModuleImagePath();
            // 上传图片的物理路径
            string fileFullPath = Server.MapPath(filePath);
            // 图片扩展名
            string strExtension = strOrgImageName.Substring(strOrgImageName.LastIndexOf(".") + 1, (strOrgImageName.Length - strOrgImageName.LastIndexOf(".") - 1));
            // 图片自动重命名
            string strNewFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + "." + strExtension;
            // 上传图片的URL 
            string pictureURL = filePath.Replace("~" + Path.DirectorySeparatorChar, string.Empty) + strNewFileName;
            // 上传图片的物理路径+文件名
            string fileFullName = Server.MapPath(filePath + strNewFileName);

            if (fileEnterprisePicture.HasFile)
            {
                if (!Directory.Exists(fileFullPath))
                {
                    Directory.CreateDirectory(fileFullPath);
                }

                fileEnterprisePicture.SaveAs(fileFullName);
            }

            // 插入图片表
            TblBizPicture item = new TblBizPicture();
            item.PictureName = strNewFileName;
            item.PictureURL = pictureURL;
            item.Save();

            // 返回图片ID
            item = new Select().From<TblBizPicture>()
              .Where(TblBizPicture.PictureNameColumn).IsEqualTo(strNewFileName)
              .ExecuteSingle<TblBizPicture>();

            return item.PictureId.ToString();

        }


        protected void gridEnterprisePicture_RowCommand(object sender, GridCommandEventArgs e)
        {
            int pictureId = Convert.ToInt32(gridEnterprisePicture.DataKeys[e.RowIndex][0]);

            if (e.CommandName == "Delete")
            {
                // 在操作之前进行权限检查
                if (!CheckPowerDelete())
                {
                    CheckPowerFailWithAlert();
                    return;
                }

                // 删除图片表数据
                TblBizPicture.Delete(pictureId);

                //TODO:图片应该同时删除，否则产生垃圾文件

                #region 更新企业表图片字段
                int intEnterpriseId = GetQueryIntValue("id");
                TblBizEnterprise item = TblBizEnterprise.FetchByID(intEnterpriseId);
                ArrayList arrlst = new ArrayList(GetDataKeyIDs(this.gridEnterprisePicture));
                // 删除单个图片
                arrlst.Remove(pictureId);
                item.EnterprisePicture = StringUtil.ConvertArrayToCommaString(arrlst);
                item.Save(User.Identity.Name);
                #endregion 更新企业表图片字段

                BindGrid();
            }
        }


        protected void btnDeleteSelected_Click(object sender, EventArgs e)
        {
            // 在操作之前进行权限检查
            if (!CheckPowerDelete())
            {
                CheckPowerFailWithAlert();
                return;
            }

            //TODO:删除图片文件

            #region 删除图片表相关记录
            // 从每个选中的行中获取ID（在Grid1中定义的DataKeyNames）
            List<int> ids = base.GetSelectedDataKeyIDs(this.gridEnterprisePicture);

            // 执行数据库操作
            new Delete().From<TblBizPicture>()
                 .Where(TblBizPicture.PictureIdColumn).In(ids)
                 .Execute();
            #endregion 删除图片表相关记录


            #region 更新企业表图片字段
            int intEnterpriseId = GetQueryIntValue("id");
            TblBizEnterprise item = TblBizEnterprise.FetchByID(intEnterpriseId);
            item.EnterprisePicture = string.Empty;
            item.Save(User.Identity.Name);
            #endregion 更新企业表图片字段

            //TODO:删除图片文件

            // 清空当前选中的项
            gridEnterprisePicture.SelectedRowIndexArray = null;

            // 重新绑定表格
            BindGrid();
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            // 上传文件、更新图片表并返回图片的文件名
            string pictureId = UploadImage();

            #region 更新企业表图片字段
            int intEnterpriseId = GetQueryIntValue("id");
            TblBizEnterprise item = TblBizEnterprise.FetchByID(intEnterpriseId);
            ArrayList arrlst = new ArrayList(GetDataKeyIDs(this.gridEnterprisePicture));
            // 追加图片（逗号分隔）
            arrlst.Add(pictureId);

            item.EnterprisePicture = StringUtil.ConvertArrayToCommaString(arrlst);
            item.Save(User.Identity.Name);
            #endregion 更新企业表图片字段

            // 清空上传控件，以便继续上传
            this.fileEnterprisePicture.Text = string.Empty;

            //// 重新绑定表格
            //BindGrid();

            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
 
        }
    }

}